package com.wash.shoes.domain.mtbusy;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.meituan.sdk.MeituanResponse;
import com.meituan.sdk.internal.exceptions.MtSdkException;
import com.meituan.sdk.model.ddzh.yuding.lifereserveMerchantmodify.LifereserveMerchantmodifyRequest;
import com.meituan.sdk.model.ddzh.yuding.merchantcancelorder.MerchantcancelorderRequest;
import com.meituan.sdk.model.ddzh.yuding.queryOrder.QueryOrderRequest;
import com.meituan.sdk.model.ddzh.yuding.queryOrder.QueryOrderResponse;
import com.meituan.sdk.model.ddzh.yuding.updateorderfulfillinfo.UpdateorderfulfillinfoRequest;
import com.meituan.sdk.model.ddzhkh.dingdan.orderReserveorderquery.OrderReserveorderqueryRequest;
import com.meituan.sdk.model.ddzhkh.dingdan.orderReserveorderquery.OrderReserveorderqueryResponse;
import com.ruoyi.common.utils.StringUtils;
import com.wash.shoes.common.enums.FulFillEnum;
import com.wash.shoes.common.enums.JdEnum;
import com.wash.shoes.common.enums.OrderStatusEnum;
import com.wash.shoes.domain.dto.ReserveDto;
import com.wash.shoes.domain.jd.JdCreateOrder;
import com.wash.shoes.entity.*;
import com.wash.shoes.exception.WashException;
import com.wash.shoes.service.*;
import com.wash.shoes.util.WashDateUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @author lijianguo
 * @Date 23/09/2024
 * 更新履约信息
 **/
@Log4j2
@Component
public class MtUpdateFulFillInfo {

    @Autowired
    OrderService orderService;

    @Autowired
    ShopService shopService;

    @Autowired
    ShoeService shoeService;

    @Autowired
    MtAuthService mtAuthService;

    @Autowired
    OrderTransportService orderTransportService;

    @Autowired
    JdCreateOrder jdCreateOrder;

    @PostConstruct
    void init() {

//        initStatus();
//        fulfillInfo("202410031921177092", FulFillEnum.COMPLETION, "余宁", "15882037762");
//       shopCancelOrder("202412123625069362");
//        ReserveDto reserveDto = new ReserveDto();
//        reserveDto.setOrderId("202409300102419934");
//        reserveDto.setReserveName("见过");
//        reserveDto.setReserveAddress("四川省成都市双流区 南湖逸家-19栋20栋");
//        reserveDto.setReservePhone("18382496398");
//        reserveDto.setBookStartTime(1727884800000L);
//        reserveDto.setBookEndTime(1727971200000L);
//        merchantModify(reserveDto);
//        fill("45317029");
    }


    /**
     * @author lijianguo
     * @Date 23/10/2024
     * 手动处理所有的订单
     **/
    public void initStatus() {

        log.info("===========  定时任务开始处理没有处理完成的订单 =================");
        //  获取今天的前6天
        String beginDate = WashDateUtil.addSecond(-3600 * 24 * 6);

        List<OrderPo> orderPos = orderService.sendShoeOrder(5, beginDate);
        for (OrderPo orderPo : orderPos) {
            ShopPo shopPo = shopService.getById(orderPo.getShopId());
            //TODO DeveloperId=114769 美团梵尘洗护已经没有卖了 会鉴权失败 这里先过滤一下
            if (Objects.nonNull(shopPo) && StringUtils.equals(shopPo.getDeveloperId(),"114769")) {
                log.info("developerId=114769 的订单，orderId={}", orderPo.getId());
                continue;
            }
            log.info("===========  =================");
            OrderTransportPo orderTransportPo = orderTransportService.getOneByOrderIdType(orderPo.getId(), "送鞋");
            String status = jdCreateOrder.orderStatus(orderTransportPo.getWayBillCode());

            //京东物流BUG，如果是送鞋中 快递小哥拒单了 重新分配任务，那么这个物流的状态一直是406
            //这里所以认为送鞋中 快递拒单了 也算成功
            if (JdEnum.ORDER_TOU_T.getStatus().equals(Integer.parseInt(status))
                    || JdEnum.ORDER_JD_DZ.getStatus().equals(Integer.parseInt(status))) {
                log.info("============== ================");
                fulfillInfo(orderPo.getId(), FulFillEnum.COMPLETION, "余宁", "15882037762");
                log.info("============== ================ {}   =={}==", orderPo.getId(), orderPo.getOrderNo());
            }
            log.info("============== 订单的id为 ========={}=======", orderPo.getOrderNo());
        }
    }

    /**
     * @author lijianguo
     * @Date 23/09/2024
     * 请输入方法的简介
     **/
    public void fulfillInfo(String orderId, FulFillEnum fulFillEnum, String servicePerson, String servicePersonPhone) {
        // 提前处理履约状态,这里只是处理mt的订单,其他的订单不需要这里处理
        OrderPo orderPo = orderService.getById(orderId);
        // /* 清洗中(洗衣) */ 如果要更新为清洗中
        log.info("履约信息 {}  订单信息:{}", fulFillEnum.getCode(), JSONObject.toJSONString(orderPo));
        if (!"2".equals(orderPo.getComeFrom())) {
            log.info("不是mt的订单,不处理数据 {}", JSONObject.toJSONString(orderPo));
            return;
        }
        // 已经到达，如果jd物流没有推送分配员工 消息这样处理
        if (FulFillEnum.ARRIVED.equals(fulFillEnum)) {
            // 没有数据，先分配，在设置,这里处理jd 物流消息没有推送的补充
            if (StrUtil.isBlank(orderPo.getFulfillStatus())) {
                fulfillInfoReal(orderPo, FulFillEnum.ALLOCATED, servicePerson, servicePersonPhone);
                log.info("FulFillEnum.ARRIVED 订单没有分配快递员工 {}", JSONObject.toJSONString(orderPo));
                // 已经分配了
                orderPo = orderService.getById(orderId);
            }
        }
        // 如果在清洗中的订单，首先要分配 和 到达
        if (FulFillEnum.CLEANING.equals(fulFillEnum)) {
            // 没有数据，先分配，在设置,这里处理jd 物流消息没有推送的补充
            if (StrUtil.isBlank(orderPo.getFulfillStatus())) {
                fulfillInfoReal(orderPo, FulFillEnum.ALLOCATED, servicePerson, servicePersonPhone);
                log.info("(FulFillEnum.CLEANING 订单没有分配快递员工 {}", JSONObject.toJSONString(orderPo));
                // 已经分配了
                orderPo = orderService.getById(orderId);
            }
            // 如果订单更新为清洗中,就需要先 当前状态为取件中，只能更新当前状态或者更新为已送达
            if (FulFillEnum.ALLOCATED.getCode().equals(orderPo.getFulfillStatus())) {
                fulfillInfoReal(orderPo, FulFillEnum.ARRIVED, servicePerson, servicePersonPhone);
                log.info("(FulFillEnum.CLEANING 订单没有送到 {}", JSONObject.toJSONString(orderPo));
            }
        }
        // 履约完成
        if (FulFillEnum.COMPLETION.equals(fulFillEnum)) {
            // 没有数据，先分配，在设置,这里处理jd 物流消息没有推送的补充
            if (StrUtil.isBlank(orderPo.getFulfillStatus())) {
                fulfillInfoReal(orderPo, FulFillEnum.ALLOCATED, servicePerson, servicePersonPhone);
                log.info("FulFillEnum.CLEANING 订单没有分配快递员工 {}", JSONObject.toJSONString(orderPo));
                // 已经分配了
                orderPo = orderService.getById(orderId);
            }
            // 如果订单更新为清洗中,就需要先 当前状态为取件中，只能更新当前状态或者更新为已送达
            if (FulFillEnum.PICKED_UP.getCode().equals(orderPo.getFulfillStatus())) {
                fulfillInfoReal(orderPo, FulFillEnum.ARRIVED, servicePerson, servicePersonPhone);
                fulfillInfoReal(orderPo, FulFillEnum.CLEANING, servicePerson, servicePersonPhone);
                fulfillInfoReal(orderPo, FulFillEnum.RETURNING, servicePerson, servicePersonPhone);
                log.info("FulFillEnum.CLEANING 订单没有送到 {}", JSONObject.toJSONString(orderPo));
            }
            // 如果订单更新为清洗中,就需要先 当前状态为取件中，只能更新当前状态或者更新为已送达
            if (FulFillEnum.ALLOCATED.getCode().equals(orderPo.getFulfillStatus())) {
                fulfillInfoReal(orderPo, FulFillEnum.ARRIVED, servicePerson, servicePersonPhone);
                fulfillInfoReal(orderPo, FulFillEnum.CLEANING, servicePerson, servicePersonPhone);
                fulfillInfoReal(orderPo, FulFillEnum.RETURNING, servicePerson, servicePersonPhone);
                log.info("FulFillEnum.CLEANING 订单没有送到 {}", JSONObject.toJSONString(orderPo));
            }

            //
            if (FulFillEnum.ARRIVED.getCode().equals(orderPo.getFulfillStatus())) {
                fulfillInfoReal(orderPo, FulFillEnum.CLEANING, servicePerson, servicePersonPhone);
                fulfillInfoReal(orderPo, FulFillEnum.RETURNING, servicePerson, servicePersonPhone);
                log.info("FulFillEnum.CLEANING 订单没有送到 {}", JSONObject.toJSONString(orderPo));
            }

            if (FulFillEnum.CLEANING.getCode().equals(orderPo.getFulfillStatus())) {
                fulfillInfoReal(orderPo, FulFillEnum.RETURNING, servicePerson, servicePersonPhone);
                log.info("FulFillEnum.CLEANING 订单没有送到 {}", JSONObject.toJSONString(orderPo));
            }
        }

        fulfillInfoReal(orderPo, fulFillEnum, servicePerson, servicePersonPhone);
    }

    /**
     * @author lijianguo
     * @Date 25/09/2024
     * 处理履约的
     **/
    private void fulfillInfoReal(OrderPo orderPo, FulFillEnum fulFillEnum, String servicePerson, String servicePersonPhone) {
        log.info("开始更新订单的履约状态 {} {} {} {}", orderPo.getId(), fulFillEnum.getCode(), servicePerson, servicePersonPhone);
        String orderId = orderPo.getId();
        OrderTransportPo orderTransportPo = orderTransportService.getOneByOrderId(orderId);
        ShopPo shopPo = shopService.getById(orderTransportPo.getShopId());
        String token = getOrderToken(orderPo.getShopId());
        if (token == null) {
            return;
        }
        // 履约信息,只需要更新美团的订单同步美团的信息
        UpdateorderfulfillinfoRequest request = new UpdateorderfulfillinfoRequest();
        request.setOrderId(orderPo.getMtOrderId());
        request.setType(2);
        request.setOrderFulfillStatus(fulFillEnum.getStatus());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("delivery_type", "2");
        //  已分配（通用) 上门取衣服中
        if (FulFillEnum.ALLOCATED.equals(fulFillEnum)) {
            jsonObject.put("service_person", servicePerson);
            jsonObject.put("service_person_phone", servicePersonPhone);
            jsonObject.put("delivery_info", "开始运输");
            jsonObject.put("express_code", "JD");
            jsonObject.put("express_number", orderTransportPo.getWayBillCode());
            jsonObject.put("express_mobile", orderTransportPo.getReceiverMobile());
        } else if (FulFillEnum.PICKED_UP.equals(fulFillEnum)) {
            // 衣物已送达--物流信息送达
            jsonObject.put("delivery_info", "衣物已送达");
        } else if (FulFillEnum.ARRIVED.equals(fulFillEnum)) {
            // 衣物已送达--物流信息送达
            jsonObject.put("delivery_info", "衣物已送达");
        } else if (FulFillEnum.CLEANING.equals(fulFillEnum)) {
            // 衣物已送达--衣物清洗中--入库的操作
            List<ShoePo> orderTransportPoList = shoeService.getByOrderId(orderId);
            List<String> picList = new ArrayList<>();
            for (ShoePo shoePo : orderTransportPoList) {
                if (StrUtil.isNotBlank(shoePo.getPicture())) {
                    String[] list = shoePo.getPicture().split(",");
                    for (String one : list) {
                        picList.add("https://shoeswasher.oss-cn-heyuan.aliyuncs.com/" + one);
                    }
                }
            }
            // 设置一张默认的图片
            if (picList.isEmpty()) {
                picList.add("https://shoeswasher.oss-cn-heyuan.aliyuncs.com/static/img/43131740386990_.pic.jpg");
            }
            jsonObject.put("delivery_info", "清洗中(洗衣)");
            JSONObject serviceVoucher = new JSONObject();
            jsonObject.put("service_voucher", serviceVoucher);
            serviceVoucher.put("general_description", "凭证描述");
            JSONArray detailList = new JSONArray();
            serviceVoucher.put("detail_list", detailList);

            for (String url : picList) {
                JSONObject oneObj = new JSONObject();
                detailList.add(oneObj);
                oneObj.put("app_sku_id", "11122233");
                oneObj.put("describe", "入库前效果");
                oneObj.put("pic_url", url);
                oneObj.put("product_title", "入库前效果");
            }
        } else if (FulFillEnum.RETURNING.equals(fulFillEnum)) {
            // 返回中(洗衣)
            jsonObject.put("service_person", servicePerson);
            jsonObject.put("service_person_phone", servicePersonPhone);
            jsonObject.put("delivery_info", "开始运输");
            jsonObject.put("express_code", "JD");
            jsonObject.put("express_number", orderTransportPo.getWayBillCode());
            jsonObject.put("express_mobile", orderTransportPo.getReceiverMobile());
        } else if (FulFillEnum.COMPLETION.equals(fulFillEnum)) {
            // 完成
            orderPo.setStatus(OrderStatusEnum.COMPLETED.getStatus());
            jsonObject.put("delivery_info", "履约完成");
        }

        request.setAttrKeyValue(jsonObject.toJSONString());

        try {
            MeituanResponse mtResponse = MtAllClient.getClient(shopPo.getDeveloperId()).invokeApi(request, token);
            log.info("美团 更新履约信息 request is {}", JSONObject.toJSONString(request));
            log.info("美团 更新履约信息 response is {}", JSONObject.toJSONString(mtResponse));
            // 履约成功更新订单的履约状态
            if ("OP_SUCCESS".equals(mtResponse.getCode())) {
                log.info("更新订单的履约状态 [{}]  为 [{}]", orderId, fulFillEnum.getCode());
                orderPo.setFulfillStatus(fulFillEnum.getCode());
                orderService.updateById(orderPo);
            }
        } catch (MtSdkException e) {
            //  这里其实是正确的数据,美团的bug
            log.error(e);
            log.info("订单物流信息更新成功 {}", orderId);
            // 履约成功更新订单的履约状态
            log.info("更新订单的履约状态 [{}]  为 [{}]", orderId, fulFillEnum.getCode());
            orderPo.setFulfillStatus(fulFillEnum.getCode());
            orderService.updateById(orderPo);
        } catch (Exception e) {
            //  这里其实是正确的数据,美团的bug
            log.error(e);
            log.info("订单物流信息更新成功 {}", orderId);
            log.info("更新订单的履约状态 [{}]  为 [{}]", orderId, fulFillEnum.getCode());
            orderPo.setFulfillStatus(fulFillEnum.getCode());
            orderService.updateById(orderPo);
        }
    }

    /**
     * @author lijianguo
     * @Date 24/09/2024
     * 取消订单，
     **/
    public void shopCancelOrder(String orderId) {

        OrderPo orderPo = orderService.getById(orderId);
        ShopPo shopPo = shopService.getById(orderPo.getShopId());

        MerchantcancelorderRequest request = new MerchantcancelorderRequest();
        request.setOrderId(orderPo.getMtOrderId());
        request.setType(2);

        // 58
        String token = mtAuthService.getLastTokenStr("58", shopPo.getOpBizCode(), null);
        if (token == null) {
            log.error("门店的token不存在 {}", shopPo.getShopName());
            return;
        }
        try {
            MeituanResponse mtResponse = MtAllClient.getClient(shopPo.getDeveloperId()).invokeApi(request, token);
            log.info("美团 商户取消订单 request is {}", JSONObject.toJSONString(request));
            log.info("美团 商户取消订单 response is {}", JSONObject.toJSONString(mtResponse));
            if (!"OP_SUCCESS".equals(mtResponse.getCode())) {
                throw new WashException(mtResponse.getMsg());
            }
        } catch (MtSdkException e) {
            log.error(e);
            throw new WashException(e.getMessage());
        } catch (Exception e) {
            log.error(e);
            throw new WashException(e.getMessage());
        }
    }

    /**
     * @author lijianguo
     * @Date 30/09/2024
     * 商家改约,主要修改约定时间和地址,物流信息为没有取件
     **/
    public void merchantModify(ReserveDto reserveDto) {

        OrderPo orderPo = orderService.getById(reserveDto.getOrderId());
        ShopPo shopPo = shopService.getById(orderPo.getShopId());
        String token = getOrderToken(orderPo.getShopId());
        if (token == null) {
            throw new WashException("商户token不存在");
        }
        LifereserveMerchantmodifyRequest request = new LifereserveMerchantmodifyRequest();
        request.setReserveOrderId(Long.valueOf(orderPo.getMtOrderId()));
        request.setReserveUserName(reserveDto.getReserveName());
        request.setReservePhone(reserveDto.getReservePhone());
        request.setReserveAddress(reserveDto.getReserveAddress());
        request.setBookStartTime(reserveDto.getBookStartTime());
        request.setBookEndTime(reserveDto.getBookEndTime());

        try {
            MeituanResponse mtResponse = MtAllClient.getClient(shopPo.getDeveloperId()).invokeApi(request, token);
            log.info("美团 商家改约 request is {}", JSONObject.toJSONString(request));
            log.info("美团 商家改约 response is {}", JSONObject.toJSONString(mtResponse));
            // 履约成功更新订单的履约状态
            if ("OP_SUCCESS".equals(mtResponse.getCode())) {
                log.info("商家改约 [{}] 成功", reserveDto.getOrderId());
            } else {
                throw new WashException(mtResponse.getMsg());
            }
        } catch (MtSdkException e) {
            //  这里其实是正确的数据,美团的bug
            log.error(e);
            // 履约成功更新订单的履约状态
            log.info("商家改约 [{}]", JSONObject.toJSONString(reserveDto));
            throw new WashException(e.getMessage());
        } catch (Exception e) {
            //  这里其实是正确的数据,美团的bug
            log.error(e);
            log.info("商家改约 [{}]", JSONObject.toJSONString(reserveDto));
            throw new WashException(e.getMessage());
        }
    }

    /**
     * @author lijianguo
     * @Date 30/09/2024
     * token
     **/
    private String getOrderToken(String shopId) {
        ShopPo shopPo = shopService.getById(shopId);
        String token = mtAuthService.getLastTokenStr("58", shopPo.getOpBizCode(), null);
        if (token == null) {
            log.error("门店的token不存在 {}", shopPo.getShopName());
            return null;
        }
        return token;
    }

    /**
     * 查询这个卷的使用状态
     */
    private String serialNumberStatus(OrderPo orderPo) {
        QueryOrderRequest request = new QueryOrderRequest();
        request.setOrderId(Long.valueOf(orderPo.getMtOrderId()));
        ShopPo shopPo = shopService.getById(orderPo.getShopId());
        String shopToken = mtAuthService.getLastTokenStr("58", shopPo.getOpBizCode(), "112891");
        try {
            MeituanResponse<QueryOrderResponse> meituanResponse = MtAllClient.getClient(shopPo.getDeveloperId()).invokeApi(request, shopToken);
            QueryOrderResponse orderResponse = meituanResponse.getData();
            log.info("result is {}", JSONObject.toJSONString(orderResponse));
        } catch (Exception e) {
            log.error(e);
            throw new WashException("订单查询失败");
        }
        return "";
    }

    /**
     * 获取订单的最新的履约状态, 返回空就为订单取消
     */
    public FulFillEnum getMtOrderStatus(OrderPo orderPo) {
        ShopPo shopPo = shopService.getById(orderPo.getShopId());
        String tokenStr = mtAuthService.getLastTokenStr("59", null, shopPo.getDeveloperId());
        OrderReserveorderqueryRequest orderRequest = new OrderReserveorderqueryRequest();
        orderRequest.setOrderIds(Collections.singletonList(Long.valueOf(orderPo.getMtOrderId())));
        try {
            MeituanResponse<OrderReserveorderqueryResponse> meituanResponse = MtAllClient.getClient(shopPo.getDeveloperId()).invokeApi(orderRequest, tokenStr);
            OrderReserveorderqueryResponse orderResponse = meituanResponse.getData();
            log.info("result is {}", JSONObject.toJSONString(orderResponse));
            // 预约单主状态，1-待接单，2-已接单，3-预约失败，4-取消中 5-已取消，6-预约改期中，7-商家已服务 8-已消费
            if (orderResponse.getResult().get(0).getStatus() == 7 || orderResponse.getResult().get(0).getStatus() == 8) {
                return FulFillEnum.COMPLETION;
            }
            // 预约单主状态，1-待接单，2-已接单，3-预约失败，4-取消中 5-已取消，6-预约改期中，7-商家已服务 8-已消费
            if (orderResponse.getResult().get(0).getStatus() == 5) {
                orderPo.setStatus(OrderStatusEnum.CANCEL.getStatus());
                orderService.updateById(orderPo);
                return FulFillEnum.COMPLETION;
            }

            // 预约的状态
            return FulFillEnum.getByStatus(orderResponse.getResult().get(0).getFulfilStatus());
        } catch (Exception e) {
            log.error(e);
            throw new WashException("订单查询失败");
        }

    }

}
